/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package DAO.Financial;

import DAO.exceptions.IllegalOrphanException;
import DAO.exceptions.NonexistentEntityException;
import DAO.exceptions.PreexistingEntityException;
import FinancialEntity.Company;
import java.io.Serializable;
import javax.persistence.Query;
import javax.persistence.EntityNotFoundException;
import javax.persistence.criteria.CriteriaQuery;
import javax.persistence.criteria.Root;
import FinancialEntity.Market;
import FinancialEntity.Stock;
import java.util.ArrayList;
import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;

/**
 *
 * @author Sebastian
 */
public class CompanyDAO implements Serializable, DAOFinancial {

    public void create(Company company, EntityManager em) throws PreexistingEntityException, Exception {
        if (company.getStockList() == null) {
            company.setStockList(new ArrayList<Stock>());
        }
        try {
            Market marketid = company.getMarketid();
            if (marketid != null) {
                marketid = em.getReference(marketid.getClass(), marketid.getId());
                company.setMarketid(marketid);
            }
            List<Stock> attachedStockList = new ArrayList<Stock>();
            for (Stock stockListStockToAttach : company.getStockList()) {
                stockListStockToAttach = em.getReference(stockListStockToAttach.getClass(), stockListStockToAttach.getStockPK());
                attachedStockList.add(stockListStockToAttach);
            }
            company.setStockList(attachedStockList);
            em.persist(company);
            if (marketid != null) {
                marketid.getCompanyList().add(company);
                marketid = em.merge(marketid);
            }
            for (Stock stockListStock : company.getStockList()) {
                Company oldCompanyOfStockListStock = stockListStock.getCompany();
                stockListStock.setCompany(company);
                stockListStock = em.merge(stockListStock);
                if (oldCompanyOfStockListStock != null) {
                    oldCompanyOfStockListStock.getStockList().remove(stockListStock);
                    oldCompanyOfStockListStock = em.merge(oldCompanyOfStockListStock);
                }
            }
        } catch (Exception ex) {
            if (findCompany(company.getId(),em) != null) {
                throw new PreexistingEntityException("Company " + company + " already exists.", ex);
            }
            throw ex;
        } 
    }

    public void edit(Company company, EntityManager em) throws IllegalOrphanException, NonexistentEntityException, Exception {
        try {
            Company persistentCompany = em.find(Company.class, company.getId());
            Market marketidOld = persistentCompany.getMarketid();
            Market marketidNew = company.getMarketid();
            List<Stock> stockListOld = persistentCompany.getStockList();
            List<Stock> stockListNew = company.getStockList();
            List<String> illegalOrphanMessages = null;
            for (Stock stockListOldStock : stockListOld) {
                if (!stockListNew.contains(stockListOldStock)) {
                    if (illegalOrphanMessages == null) {
                        illegalOrphanMessages = new ArrayList<String>();
                    }
                    illegalOrphanMessages.add("You must retain Stock " + stockListOldStock + " since its company field is not nullable.");
                }
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            if (marketidNew != null) {
                marketidNew = em.getReference(marketidNew.getClass(), marketidNew.getId());
                company.setMarketid(marketidNew);
            }
            List<Stock> attachedStockListNew = new ArrayList<Stock>();
            for (Stock stockListNewStockToAttach : stockListNew) {
                stockListNewStockToAttach = em.getReference(stockListNewStockToAttach.getClass(), stockListNewStockToAttach.getStockPK());
                attachedStockListNew.add(stockListNewStockToAttach);
            }
            stockListNew = attachedStockListNew;
            company.setStockList(stockListNew);
            company = em.merge(company);
            if (marketidOld != null && !marketidOld.equals(marketidNew)) {
                marketidOld.getCompanyList().remove(company);
                marketidOld = em.merge(marketidOld);
            }
            if (marketidNew != null && !marketidNew.equals(marketidOld)) {
                marketidNew.getCompanyList().add(company);
                marketidNew = em.merge(marketidNew);
            }
            for (Stock stockListNewStock : stockListNew) {
                if (!stockListOld.contains(stockListNewStock)) {
                    Company oldCompanyOfStockListNewStock = stockListNewStock.getCompany();
                    stockListNewStock.setCompany(company);
                    stockListNewStock = em.merge(stockListNewStock);
                    if (oldCompanyOfStockListNewStock != null && !oldCompanyOfStockListNewStock.equals(company)) {
                        oldCompanyOfStockListNewStock.getStockList().remove(stockListNewStock);
                        oldCompanyOfStockListNewStock = em.merge(oldCompanyOfStockListNewStock);
                    }
                }
            }
        } catch (Exception ex) {
            String msg = ex.getLocalizedMessage();
            if (msg == null || msg.length() == 0) {
                Integer id = company.getId();
                if (findCompany(id, em) == null) {
                    throw new NonexistentEntityException("The company with id " + id + " no longer exists.");
                }
            }
            throw ex;
        } 
    }

    public void destroy(Integer id, EntityManager em) throws IllegalOrphanException, NonexistentEntityException {
            Company company;
            try {
                company = em.getReference(Company.class, id);
                company.getId();
            } catch (EntityNotFoundException enfe) {
                throw new NonexistentEntityException("The company with id " + id + " no longer exists.", enfe);
            }
            List<String> illegalOrphanMessages = null;
            List<Stock> stockListOrphanCheck = company.getStockList();
            for (Stock stockListOrphanCheckStock : stockListOrphanCheck) {
                if (illegalOrphanMessages == null) {
                    illegalOrphanMessages = new ArrayList<String>();
                }
                illegalOrphanMessages.add("This Company (" + company + ") cannot be destroyed since the Stock " + stockListOrphanCheckStock + " in its stockList field has a non-nullable company field.");
            }
            if (illegalOrphanMessages != null) {
                throw new IllegalOrphanException(illegalOrphanMessages);
            }
            Market marketid = company.getMarketid();
            if (marketid != null) {
                marketid.getCompanyList().remove(company);
                marketid = em.merge(marketid);
            }
            em.remove(company);
            
    }

    public List<Company> findCompanyEntities(EntityManager em) {
        return findCompanyEntities(true, -1, -1, em);
    }

    public List<Company> findCompanyEntities(int maxResults, int firstResult, EntityManager em) {
        return findCompanyEntities(false, maxResults, firstResult, em);
    }

    private List<Company> findCompanyEntities(boolean all, int maxResults, int firstResult, EntityManager em) {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            cq.select(cq.from(Company.class));
            Query q = em.createQuery(cq);
            if (!all) {
                q.setMaxResults(maxResults);
                q.setFirstResult(firstResult);
            }
            return q.getResultList();
    }

    public Company findCompany(Integer id, EntityManager em) {
            return em.find(Company.class, id);
    }

    public int getCompanyCount(EntityManager em) {
            CriteriaQuery cq = em.getCriteriaBuilder().createQuery();
            Root<Company> rt = cq.from(Company.class);
            cq.select(em.getCriteriaBuilder().count(rt));
            Query q = em.createQuery(cq);
            return ((Long) q.getSingleResult()).intValue();
    }
    
}
